/**
 * 工况特定输出参数表前端管理JS
 */

try {
    // API基础路径
    let aapOutputAPI_BASE = '/api/feibiao/aap/output';

    // 跟踪当前页码和每页大小
    let currentPage = 0;
    let pageSize = 10;
    let currentSort = 'id,desc';


    // 在DOM加载完成后设置API基础路径
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof API_BASE !== 'undefined') {
            aapOutputAPI_BASE = `${API_BASE}/feibiao/aap/output`;
        }
    });

    /**
     * 加载工况特定输出参数表列表
     */
    function loadAapOutputList(page = 0, size = 10, sort = 'id,asc') {
        currentPage = page;
        pageSize = size;
        currentSort = sort;

        const mainContent = document.getElementById('mainContent');
        mainContent.innerHTML = '<div class="loading">数据加载中...</div>';

        fetch(`${aapOutputAPI_BASE}?page=${page}&size=${size}&sort=${sort}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                renderAapOutputTable(data);
            })
            .catch(error => {
                console.error('获取数据失败:', error);
                mainContent.innerHTML = `<div class="error-container">加载失败: ${error.message}</div>`;
            });
    }

    /**
     * 渲染工况特定输出参数表
     * @param {Object} data - 分页数据
     */
    function renderAapOutputTable(data) {
        const mainContent = document.getElementById('mainContent');
        let html = `
        <div class="content-header">
            <h2 class="content-title">工况特定输出参数表</h2>
            <button class="btn btn-primary" onclick="showAapOutputForm()">新增</button>
        </div>
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索...">
            <button class="search-btn" onclick="searchAapOutput()">搜索</button>
        </div>
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>电机ID</th>
                    <th>电机状态</th>
                    <th>置信度</th>
                    <th>异常分数</th>
                    <th>剩余寿命(小时)</th>
                    <th>下次检查时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
        `;

        if (data.content && data.content.length > 0) {
            data.content.forEach(item => {
                html += `
                <tr>
                    <td>${item.id || ''}</td>
                    <td>${item.motorId || ''}</td>
                    <td>${item.motorState || ''}</td>
                    <td>${item.confidenceScore || ''}</td>
                    <td>${item.anomalyScore || ''}</td>
                    <td>${item.remainingUsefulLife || ''}</td>
                    <td>${item.nextInspectionTime ? new Date(item.nextInspectionTime).toLocaleString() : ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewAapOutput(${item.id})">查看</a>
                        <a href="javascript:void(0)" onclick="editAapOutput(${item.id})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteAapOutput(${item.id})">删除</a>
                    </td>
                </tr>
            `;
            });
        } else {
            html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
        }

        html += `
            </tbody>
        </table>
        `;

        if (data.totalPages > 0) {
            html += `
            <ul class="pagination">
                <li class="${currentPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                </li>
            `;

            for (let i = 0; i < data.totalPages; i++) {
                if (i === currentPage) {
                    html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
                } else {
                    html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
                }
            }

            html += `
                <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                </li>
            </ul>
            `;
        }

        mainContent.innerHTML = html;
    }

    /**
     * 跳转到指定页码
     * @param {number} page - 页码
     */
    function gotoPage(page) {
        loadAapOutputList(page, pageSize, currentSort);
    }

    /**
     * 搜索工况特定输出参数表
     */
    function searchAapOutput() {
        const keyword = document.getElementById('searchInput').value.trim();
        currentPage = 0;

        let url = `${aapOutputAPI_BASE}/search?page=${currentPage}&size=${pageSize}`;
        if (keyword) {
            url += `&keyword=${encodeURIComponent(keyword)}`;
        }

        const mainContent = document.getElementById('mainContent');
        mainContent.innerHTML = '<div class="loading">数据加载中...</div>';

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                renderAapOutputTable(data);
            })
            .catch(error => {
                console.error('搜索失败:', error);
                showMessage('搜索失败: ' + error.message, 'error');
            });
    }

    /**
     * 查看工况特定输出参数表详情
     * @param {number} id - 记录ID
     */
    function viewAapOutput(id) {
        fetch(`${aapOutputAPI_BASE}/${id}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                showAapOutputDetail(data);
            })
            .catch(error => {
                console.error('获取详情失败:', error);
                showMessage('获取详情失败: ' + error.message, 'error');
            });
    }

    /**
     * 显示工况特定输出参数表详情
     * @param {Object} data - 详情数据
     */
    function showAapOutputDetail(data) {
        const mainContent = document.getElementById('mainContent');
        let html = `
        <div class="content-header">
            <h2 class="content-title">工况特定输出参数详情</h2>
            <button class="btn btn-default" onclick="loadAapOutputList()">返回列表</button>
        </div>
        <div class="data-detail">
            <div class="detail-group">
                <label>ID:</label>
                <div>${data.id || '--'}</div>
            </div>
            <div class="detail-group">
                <label>电机ID:</label>
                <div>${data.motorId || '--'}</div>
            </div>
            <div class="detail-group">
                <label>电机状态:</label>
                <div>${data.motorState || '--'}</div>
            </div>
            <div class="detail-group">
                <label>置信度:</label>
                <div>${data.confidenceScore || '--'}</div>
            </div>
            <div class="detail-group">
                <label>异常分数:</label>
                <div>${data.anomalyScore || '--'}</div>
            </div>
            <div class="detail-group">
                <label>剩余使用寿命:</label>
                <div>${data.remainingUsefulLife || '--'}小时</div>
            </div>
            <div class="detail-group">
                <label>下次检查时间:</label>
                <div>${data.nextInspectionTime ? new Date(data.nextInspectionTime).toLocaleString() : '--'}</div>
            </div>
            <div class="detail-group">
                <label>状态概率:</label>
                <div>${data.stateProbabilities || '--'}</div>
            </div>
            <div class="detail-group">
                <label>组件健康状况:</label>
                <div>${data.componentHealth || '--'}</div>
            </div>
            <div class="detail-group">
                <label>故障概率:</label>
                <div>${data.faultProbabilities || '--'}</div>
            </div>
            <div class="detail-group">
                <label>维护建议:</label>
                <div>${data.maintenanceRecommendations || '--'}</div>
            </div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editAapOutput(${data.id})">编辑</button>
                <button class="btn btn-danger" onclick="deleteAapOutput(${data.id})">删除</button>
                <button class="btn btn-default" onclick="loadAapOutputList()">返回</button>
            </div>
        </div>
        `;
        mainContent.innerHTML = html;
    }

    /**
     * 显示工况特定输出参数表单(新增/编辑)
     * @param {Object} data - 已有数据(编辑时传入)
     */
    function showAapOutputForm(data = null) {
        const mainContent = document.getElementById('mainContent');
        const isEdit = data !== null;
        let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}工况特定输出参数</h2>
            <button class="btn btn-default" onclick="loadAapOutputList()">返回列表</button>
        </div>
        <form id="aapOutputForm" class="data-form">
            ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
            <div class="form-group">
                <label for="motorId">电机ID <span class="required">*</span></label>
                <input type="text" id="motorId" name="motorId" class="form-control" value="${isEdit && data.motorId ? data.motorId : ''}" required>
            </div>
            <div class="form-group">
                <label for="motorState">电机状态 <span class="required">*</span></label>
                <select id="motorState" name="motorState" class="form-control" required>
                    <option value="">-- 请选择 --</option>
                    <option value="正常" ${isEdit && data.motorState === '正常' ? 'selected' : ''}>正常</option>
                    <option value="关注" ${isEdit && data.motorState === '关注' ? 'selected' : ''}>关注</option>
                    <option value="警告" ${isEdit && data.motorState === '警告' ? 'selected' : ''}>警告</option>
                    <option value="危险" ${isEdit && data.motorState === '危险' ? 'selected' : ''}>危险</option>
                </select>
            </div>
            <div class="form-group">
                <label for="confidenceScore">置信度 <span class="required">*</span></label>
                <input type="number" id="confidenceScore" name="confidenceScore" class="form-control" step="0.01" min="0" max="1" value="${isEdit && data.confidenceScore ? data.confidenceScore : ''}" required>
            </div>
            <div class="form-group">
                <label for="anomalyScore">异常分数 <span class="required">*</span></label>
                <input type="number" id="anomalyScore" name="anomalyScore" class="form-control" step="0.01" min="0" max="1" value="${isEdit && data.anomalyScore ? data.anomalyScore : ''}" required>
            </div>
            <div class="form-group">
                <label for="remainingUsefulLife">剩余使用寿命(小时) <span class="required">*</span></label>
                <input type="number" id="remainingUsefulLife" name="remainingUsefulLife" class="form-control" step="0.1" min="0" value="${isEdit && data.remainingUsefulLife ? data.remainingUsefulLife : ''}" required>
            </div>
            <div class="form-group">
                <label for="nextInspectionTime">下次检查时间 <span class="required">*</span></label>
                <input type="datetime-local" id="nextInspectionTime" name="nextInspectionTime" class="form-control" value="${isEdit && data.nextInspectionTime ? data.nextInspectionTime.substring(0, 16) : ''}" required>
            </div>
            <div class="form-group">
                <label for="stateProbabilities">状态概率(JSON格式) <span class="required">*</span></label>
                <textarea id="stateProbabilities" name="stateProbabilities" class="form-control" required>${isEdit && data.stateProbabilities ? data.stateProbabilities : '{"正常": 0.8, "异常": 0.2}'}</textarea>
            </div>
            <div class="form-group">
                <label for="componentHealth">组件健康状况(JSON格式) <span class="required">*</span></label>
                <textarea id="componentHealth" name="componentHealth" class="form-control" required>${isEdit && data.componentHealth ? data.componentHealth : '{"轴承": 0.9, "定子": 0.95, "转子": 0.85}'}</textarea>
            </div>
            <div class="form-group">
                <label for="faultProbabilities">故障概率(JSON格式) <span class="required">*</span></label>
                <textarea id="faultProbabilities" name="faultProbabilities" class="form-control" required>${isEdit && data.faultProbabilities ? data.faultProbabilities : '{"轴承故障": 0.05, "定子短路": 0.02, "绕组过热": 0.03}'}</textarea>
            </div>
            <div class="form-group">
                <label for="maintenanceRecommendations">维护建议 <span class="required">*</span></label>
                <textarea id="maintenanceRecommendations" name="maintenanceRecommendations" class="form-control" required>${isEdit && data.maintenanceRecommendations ? data.maintenanceRecommendations : '建议定期检查轴承润滑情况'}</textarea>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadAapOutputList()">取消</button>
            </div>
        </form>
        `;
        mainContent.innerHTML = html;
        document.getElementById('aapOutputForm').addEventListener('submit', function (e) {
            e.preventDefault();
            saveAapOutput(this, isEdit);
        });
    }

    /**
     * 编辑工况特定输出参数
     * @param {number} id - 记录ID
     */
    function editAapOutput(id) {
        fetch(`${aapOutputAPI_BASE}/${id}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                showAapOutputForm(data);
            })
            .catch(error => {
                console.error('获取详情失败:', error);
                showMessage('获取详情失败: ' + error.message, 'error');
            });
    }

    /**
     * 保存工况特定输出参数
     * @param {HTMLFormElement} form - 表单元素
     * @param {boolean} isEdit - 是否为编辑模式
     */
    function saveAapOutput(form, isEdit) {
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        const formData = new FormData(form);
        const data = {};
        formData.forEach((value, key) => {
            data[key] = value;
        });

        if (data.confidenceScore) data.confidenceScore = parseFloat(data.confidenceScore);
        if (data.anomalyScore) data.anomalyScore = parseFloat(data.anomalyScore);
        if (data.remainingUsefulLife) data.remainingUsefulLife = parseFloat(data.remainingUsefulLife);

        const url = isEdit ? `${aapOutputAPI_BASE}/${data.id}` : `${aapOutputAPI_BASE}`;
        const method = isEdit ? 'PUT' : 'POST';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text);
                    });
                }
                return response.json();
            })
            .then(result => {
                showMessage(`工况特定输出参数${isEdit ? '更新' : '添加'}成功!`, 'success');
                loadAapOutputList();
            })
            .catch(error => {
                console.error('保存失败:', error);
                showMessage(`保存失败: ${error.message}`, 'error');
            });
    }

    /**
     * 删除工况特定输出参数
     * @param {number} id - 记录ID
     */
    function deleteAapOutput(id) {
        if (!confirm('确定要删除这条记录吗？此操作不可恢复!')) {
            return;
        }
        fetch(`${aapOutputAPI_BASE}/${id}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text);
                    });
                }
                showMessage('删除成功!', 'success');
                loadAapOutputList();
            })
            .catch(error => {
                console.error('删除失败:', error);
                showMessage('删除失败: ' + error.message, 'error');
            });
    }

    /**
     * 显示消息提示
     * @param {string} msg - 消息内容
     * @param {string} type - 消息类型：success, error, warn, info
     */
    function showMessage(msg, type) {
        // 检查是否有全局的 showMessage 函数
        if (typeof window.showMessage === 'function' && window.showMessage !== showMessage) {
            window.showMessage(msg, type);
        } else {
            // 如果没有全局函数，使用简单的 alert
            alert(msg);
        }
    }

    // 将所有函数暴露到全局作用域
    window.loadAapOutputList = loadAapOutputList;
    window.renderAapOutputTable = renderAapOutputTable;
    window.gotoPage = gotoPage;
    window.searchAapOutput = searchAapOutput;
    window.viewAapOutput = viewAapOutput;
    window.showAapOutputDetail = showAapOutputDetail;
    window.showAapOutputForm = showAapOutputForm;
    window.editAapOutput = editAapOutput;
    window.saveAapOutput = saveAapOutput;
    window.deleteAapOutput = deleteAapOutput;

} catch (error) {
    console.error('工况特定输出参数表模块加载失败:', error);
    
    // 如果出错，仍尝试暴露关键函数
    if (typeof loadAapOutputList === 'function') {
        window.loadAapOutputList = loadAapOutputList;
    } else {
        // 提供一个备用的loadAapOutputList函数，显示错误消息
        window.loadAapOutputList = function() {
            const mainContent = document.getElementById('mainContent');
            if (mainContent) {
                mainContent.innerHTML = `
                    <div class="error-container">
                        <h3>模块加载错误</h3>
                        <p>工况特定输出参数表模块加载失败: ${error.message}</p>
                    </div>
                `;
            }
            console.error('工况特定输出参数表模块加载失败:', error);
            
            // 如果存在全局showMessage函数，显示错误
            if (typeof window.showMessage === 'function') {
                window.showMessage('工况特定输出参数表模块加载失败: ' + error.message, 'error');
            }
        };
    }
}